<template>
	<div class="system-add-dept-container">
		<el-drawer title="添加系统字典" v-model="showWindows" @close="onCancel">
			<el-form ref="formRef" :model="sysDictItem" :rules="rules" size="small" label-width="30%" style="width: 90%">
				<el-form-item label="字典编码" prop="itemCode">
					<el-input v-model="sysDictItem.itemCode" placeholder="请输入字典编码">
						<template #prepend>{{ dictCode }}</template>
					</el-input>
				</el-form-item>
				<el-form-item label="字典名称" prop="itemName">
					<el-input v-model="sysDictItem.itemName" placeholder="请输入字典名称" />
				</el-form-item>
				<el-form-item label="是否必选" prop="mandatory">
					<el-switch v-model="sysDictItem.mandatory"></el-switch>
				</el-form-item>
        <el-form-item label="是否平台" prop="mandatory">
          <el-switch v-model="sysDictItem.platform"></el-switch>
        </el-form-item>
				<el-form-item label="是否只读" prop="readonly">
					<el-switch v-model="sysDictItem.readonly"></el-switch>
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="sysDictItem.sort" placeholder="请输入字典排序" style="width: 100%" />
				</el-form-item>
				<div class="el-drawer__footer">
					<el-button @click="onCancel" size="small">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="small">添 加</el-button>
				</div>
			</el-form>
		</el-drawer>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref } from 'vue';
import { addDictItem } from '/@/api/sys/dict/index';
import { ElMessage } from 'element-plus';

export default {
	name: 'addDictItem',
	emits: ['initDictItemData'],
	props: {},
	setup(props, context) {
		const formRef = ref();

		const state = reactive({
			showWindows: false,
			dictCode: '',
			sysDictItem: {
				dicId: '',
				itemCode: '',
				itemName: '',
				mandatory: false,
				readonly: false,
        platform: false,
				sort: 0,
			},
			rules: {
				itemCode: [{ required: true, message: '字典项编码不能为空', trigger: 'blur' }],
				itemName: [{ required: true, message: '字典项名称不能为空', trigger: 'blur' }],
			},
		});

		//打开添加窗口
		const openWindows = (dictId: any, dictCode: any) => {
			state.sysDictItem.dicId = dictId;
			state.dictCode = dictCode;
			state.showWindows = true;
		};

		//取消
		const onCancel = () => {
			formRef.value.resetFields();
			state.showWindows = false;
		};

		//提交
		const onSubmit = () => {
			formRef.value.validate((valid: any) => {
				if (valid) {
					state.sysDictItem.itemCode = state.dictCode + '.' + state.sysDictItem.itemCode;
					addDictItem(state.sysDictItem.dicId, state.sysDictItem).then((res: any) => {
						if (res.code == 200) {
							onCancel();
							context.emit('initDictItemData');
						} else {
							ElMessage.error(res.message);
						}
					});
				}
			});
		};
		return {
			formRef,
			openWindows,
			onCancel,
			onSubmit,
			...toRefs(state),
		};
	},
};
</script>
